package com.hucc.sqlitedemo;

import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by l on 2017/5/10.
 */

public class CursorActivity extends AppCompatActivity {

    private SQLiteDatabase db;
    private ListView mListView;
    private SQLiteHelper mHelper;

   private final String DATABASE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/vote";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        mListView = (ListView)findViewById(R.id.list_view);

        mHelper = new SQLiteHelper(this);

        db = openDatabase(this);
        db = mHelper.getReadableDatabase();
     //   db = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
        Cursor cursor = db.rawQuery("select * from " + Constant.TABLE_NAME, null);

        MyCursorAdapter mAdapter = new MyCursorAdapter(this, cursor, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        mListView.setAdapter(mAdapter);
    }

    private SQLiteDatabase openDatabase(Context context) {
        File file = new File(DATABASE_PATH);
        //查看数据库文件是否存在
        if (file.exists()){
            Log.i("test", "存在数据库");
            // 存在则直接返回打开的数据库
            return SQLiteDatabase.openOrCreateDatabase(file, null);
        }else{
            //不存在先创建文件夹
            File path = new File(DATABASE_PATH);
            Log.i("test", "pathStr="+path);
            if (path.mkdir()){
                Log.i("test", "创建成功");
            }else{
                Log.i("test", "创建失败");
            }
            try {
                //得到资源
                AssetManager am = context.getAssets();
                //得到数据库的输入流
                // InputStream is = am.open(Constant.DATABASE_NAME);
                // InputStream is = am.open("info.db");
                InputStream is = am.open(String.valueOf(R.raw.info));
                Log.i("test", is+"");
                //用输出流写到SDcard上面
                FileOutputStream fos = new FileOutputStream(file);
                Log.i("test", "fos="+fos);
                Log.i("test", "file="+file);
                //创建byte数组  用于1KB写一次
                byte[] buffer = new byte[1024];
                int count = 0;
                while ((count = is.read(buffer))>0){
                    Log.i("test", "得到");
                    fos.write(buffer, 0, count);
                }
                fos.flush();
                fos.close();
                is.close();
            }catch (IOException e){
                e.printStackTrace();
                return null;
            }
        }
        return openDatabase(context);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        db.close();
    }

    /**
     *  以内部类的定义形式适配器
     */
    public class MyCursorAdapter extends CursorAdapter{
        // 必须定义的构造函数
        public MyCursorAdapter(Context context, Cursor cursor, int flagRegisterContentObserver) {
            super(context, cursor, flagRegisterContentObserver);
        }

        /**
         *  表示创建适配器控件中每个item对应的view对象
         * @param context 上下文
         * @param cursor  数据源cursor对象
         * @param parent  当前item的父布局
         * @return  每项item的view对象
         */
        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            View view = LayoutInflater.from(context).inflate(R.layout.list_item,null);
            return view;
        }

        /**
         *  通过newview()方法确定了每个item展示的view对象，在bindview()对布局中的控件进行填充
         * @param view 由newView()返回的每项view对象
         * @param context  上下文
         * @param cursor  数据源cursor对象
         */
        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            TextView tv_id = (TextView) view.findViewById(R.id.tv_id);
            TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
            TextView tv_phone = (TextView) view.findViewById(R.id.tv_phone);

            tv_id.setText(cursor.getInt(cursor.getColumnIndex(Constant._ID))+"");
            tv_name.setText(cursor.getString(cursor.getColumnIndex(Constant.NAME)));
            tv_phone.setText(cursor.getInt(cursor.getColumnIndex(Constant.PHONE))+"");
        }
    }
}
